<?php

namespace app\admin\controller\daily;
use app\admin\model\statistics\Exchange as Elog;
use think\Db;
use Exception;
/**
 * 每日充值统计（统计充值总金额，新充总金额，充值用户总数，新充用户数，充值均值，新用户充值均值）
 *
 * @icon fa fa-circle-o
 */
class Exchange
{
    
    /**
     * Exchange模型对象
     * @var \app\admin\model\Exchange
     */
    protected $model = null;

    public function _initialize()
    {
        $this->model = new \app\admin\model\finance\Exchange();
    }
    
    public function index()
    {
        $elog_model = new Elog();
        //获取昨日起始时间
        $begin_time = mktime(0,0,0,date('m'),date('d')-1,date('Y'));
        $end_time = mktime(0,0,0,date('m'),date('d'),date('Y'));
        //昨日日期
        $last = $end_time - 1;
        //查询是否已记录
        $row = $elog_model::get(['datetime'=>$last]);
        if(!$row){
            $where['createtime'] = ['between',[$begin_time,$end_time]];
            //充值总金额
            $total_sum = Db::name('exchange')->where($where)->field('sum(price) as sum')->find();
            //无充值不记录
            if($total_sum > 0){
                //充值用户总数
                $total_user = Db::name('exchange')->where($where)->field('count(uid) as count')->group('uid')->find();
                //新充总金额
                $new_sum = Db::name('exchange')->where($where)->where(['is_first'=>1])->field('sum(price) as sum')->find();
                //新用户充值总数
                $new_user = Db::name('exchange')->where($where)->where(['is_first'=>1])->field('count(uid) as count')->group('uid')->find();
                //充值均值
                $average = $total_sum['sum'] == 0 || $total_user['count'] == 0 ? 0 :round($total_sum['sum']/$total_user['count'],2);
                //新用户充值均值
                $new_average = $new_sum['sum'] == 0 || $new_user['count'] == 0 ? 0 :round($new_sum['sum']/$new_user['count'],2);
                //记录数据
                $data = [
                    'total_sum'     => $total_sum['sum'] ?: 0,
                    'total_user'    => $total_user['count'] ?: 0,
                    'new_sum'       => $new_sum['sum'] ?: 0,
                    'new_user'      => $new_user['count'] ?: 0,
                    'average'       => $average,
                    'new_average'   => $new_average,
                    'datetime'          => $last,
                ];

                $elog_model->save($data);
            
            }
        }
        
        
    }


    
    

}
